//
//  WKViewController.m
//  WKWebView之WebViewJavascriptBridge
//
//  Created by mingjun zhang on 2017/10/13.
//  Copyright © 2017年 mingjun zhang. All rights reserved.
//

#import "WKViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import "WKWebViewJavascriptBridge.h"
#import "HLAudioPlayer.h"

@interface WKViewController ()<WKNavigationDelegate,WKUIDelegate>

@property (strong, nonatomic)   WKWebView       *webView;
@property (strong, nonatomic)   UIProgressView  *progressView;
@property WKWebViewJavascriptBridge *bridge;

@end

@implementation WKViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"WKWebViewJavascriptBridge";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self initWebView]; //初始化webVierw
    
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];
    [_bridge setWebViewDelegate:self];
    
     [self initProgressView];//初始化进度条
    
    [self registerNaticeFunctions]; //集中方法
    
     [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}


//初始化webVierw
-(void)initWebView{
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 30.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 84) configuration:configuration];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    NSURL *path = [[NSBundle mainBundle] URLForResource:@"zenmeyang" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
    
}

//初始化进度条
-(void)initProgressView{
    
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
    
}

//导航栏方法
- (void)rightClick{

    /*
     //如果不需要参数，不需要回调，使用这个
     [_bridge callHandler:@"testJSFunction"];
     
     //如果需要参数不需要回调，使用这个
     [_bridge callHandler:@"testJSFunction" data:@"我是个学习能力还好的人"];
     
     */
    
    //既需要参数，有需要回调，使用这个
    [_bridge callHandler:@"testJSFunction" data:@"我是个学习能力还好的人" responseCallback:^(id responseData) {
        NSLog(@"调用完JS后的回调-----%@",responseData);
    }];
    
}

#pragma 集中方法
-(void)registerNaticeFunctions{
    
    [self registScanFunction]; //扫一扫
    [self registerGetLocation]; //获取定位
    [self registerBGColorFunction]; //改变背景颜色
    [self registerShare];   //执行分享功能
    [self registerPay];  //执行支付功能
    [self registerShakeFunction]; //摇一摇功能
    [self registerGoBackFunction]; //返回功能的按钮
}


//扫一扫
-(void)registScanFunction{
    
    //注册handler 供JS调用OC : OC传值或方法让JS使用
    [_bridge registerHandler:@"scanClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        NSLog(@"%@----%@",@"扫一扫",data);
        NSString *scanRsult = @"http://www.baidu.com";
        responseCallback(scanRsult);
    }];
    
}

//获取定位
-(void)registerGetLocation{
    
    [_bridge registerHandler:@"locationClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        NSLog(@"%@",data);
        
        //获取位置信息
        NSString * location = @"杭州市西湖区骆家庄";
        //将结果返回给JS
        responseCallback(location);
        
    }];
    
}

//改变背景颜色
-(void)registerBGColorFunction{
    
    __weak typeof(self) weakSelf = self;
    [_bridge registerHandler:@"colorClick" handler:^(id data, WVJBResponseCallback responseCallback) {
       //data 的类型与JS中传的参数有关
        NSDictionary *dict = data;
     
        CGFloat r = [[dict objectForKey:@"r"] floatValue];
        CGFloat g = [[dict objectForKey:@"g"] floatValue];
        CGFloat b = [[dict objectForKey:@"b"] floatValue];
        CGFloat a = [[dict objectForKey:@"a"] floatValue];
        
     weakSelf.view.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];

    }];
    
}

//分享
-(void)registerShare{
    
    [_bridge registerHandler:@"shareClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        //data的类型与JS中传的参数有关
        NSDictionary *dict = data;
        //在这里执行分享的操作
        NSString *title = [dict objectForKey:@"title"];
        NSString *content = [dict objectForKey:@"content"];
        NSString *url = [dict objectForKey:@"url"];
        
        //将分享的结果返回到JS中
        NSString *result = [NSString stringWithFormat:@"分享成功：%@%@%@",title,content,url];
        NSLog(@"%@", result);
        responseCallback(result);
        
    }];
    
}


//支付功能
-(void)registerPay{
    
    [_bridge registerHandler:@"payClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        //data 的类型与 JS中传的参数有关
        NSDictionary *dict = data;
        
        NSString *oder = [dict objectForKey:@"order_no"];
        NSInteger acount = [[dict objectForKey:@"amount"] integerValue];
        NSString *channel = [dict objectForKey:@"channel"];
        NSString *subject = [dict objectForKey:@"subject"];
        
        //  将分享的结果返回到JS中
        NSString *result = [NSString stringWithFormat:@"%@%ld%@%@",oder,acount,channel,subject];
        responseCallback(result);
    }];
    
}

//摇一摇功能
-(void)registerShakeFunction{

    [_bridge registerHandler:@"shakeClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        [HLAudioPlayer playSound:@"shake_sound_male.wav"];
        
    }];

}


//返回功能的按钮
-(void)registerGoBackFunction{
    
    __weak typeof(self) weakSelf = self;
    [_bridge registerHandler:@"goback" handler:^(id data, WVJBResponseCallback responseCallback) {
        if ([weakSelf.webView  canGoBack]) {
             [weakSelf.webView goBack];
        }
    }];

}


#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

- (void)dealloc{
    
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - WKNavigationDelegate


#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}




@end
